package cn.edu.bzu.manager.computer.controller;

import cn.edu.bzu.manager.computer.entity.CpuBrand;
import cn.edu.bzu.manager.computer.entity.CpuInfo;
import cn.edu.bzu.manager.computer.service.CpuService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * CPU信息控制器
 * 返回值均为JSON类型
 *
 * @author 1923111017张铭宸
 * @since 1.8
 */

@RequestMapping("/cpu")
@RestController
@AllArgsConstructor
public class CpuController {

    private final CpuService cpuService;

    /**
     * GET
     * 使用CPU信息ID获取CPU信息
     *
     * @param id CPU信息ID
     * @return 该ID对应的CPU信息
     */
    @GetMapping("/{id}")
    public CpuInfo showCpuInfoById(@PathVariable("id") Integer id) {
        return cpuService.findCpuInfoById(id);
    }

    /**
     * GET
     *
     * @return 所有CPU信息
     */
    @GetMapping("/all")
    public List<CpuInfo> showAllCpuInfo() {
        return cpuService.findAllCpuInfos();
    }

    /**
     * GET
     *
     * @return 所有CPU品牌
     */
    @GetMapping("/brand/all")
    public List<CpuBrand> showAllCpuBrands() {
        return cpuService.findAllCpuBrands();
    }

    /**
     * PUT
     * 更新CPU信息
     *
     * @param cpuInfo 根据请求自动绑定CPU对象
     * @return 是否成功更新
     */
    @PutMapping("/{id}")
    public boolean updateCpu(@RequestBody CpuInfo cpuInfo) {
        try {
            cpuService.saveCpuInfo(cpuInfo);
            return true;
        } catch (Exception ignored) {
        }
        return false;
    }

    /**
     * DELETE
     * 通过ID删除CPU信息
     *
     * @param id CPU信息ID
     */
    @DeleteMapping("/{id}")
    public void deleteCpuInfoById(@PathVariable Integer id) {
        cpuService.deleteCpuInfoById(id);
    }

    // 更新添加品牌
    @PutMapping("/brand/{id}")
    public CpuBrand updateCpuBrand(@RequestBody CpuBrand cpuBrand) {
        return cpuService.saveCpuBrand(cpuBrand);
    }

    /**
     * DELETE
     * 根据CPU品牌ID删除CPU品牌
     *
     * @param id 从地址获取的品牌ID
     */
    @DeleteMapping("/brand/{id}")
    public void deleteCpuBrand(@PathVariable Integer id) {
        cpuService.deleteCpuBrandById(id);
    }

}
